import { debounce } from "lodash-es";

interface DebounceOptions {
  leading?: boolean;
  maxWait?: number;
  trailing?: boolean;
  wait?: number;
}

type Fn = (...args: any) => any;

function useDebounce(fn: Fn, options?: DebounceOptions) {
  const wait = options?.wait ?? 1000;

  const debounced = debounce(
    (...arg) => {
      return fn(...arg);
    },
    wait,
    options
  );

  return {
    run: debounced,
    cancel: debounced.cancel,
    flush: debounced.flush,
  };
}

export default useDebounce;
